import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_web_test/pages/snake/EventBus.dart';
import 'package:flutter_web_test/pages/snake/SnakeHome2.dart';
import 'package:flutter_web_test/utils/SnakeGame.dart';

///蛇
class SnakeWidget extends StatefulWidget {
  SnakeWidget(
      {Key? key,
      this.columns = 20,
      this.width = 300,
      this.height,
      this.speed = 500})
      : super(key: key) {
    height ??= width;

    _board =
        CheckerBoard(columns: columns, width: width, height: height as double);

    _snake = Snake((_board as CheckerBoard).getOrigin(),
        (_board as CheckerBoard).cellwidth);
  }

  // 速度
  int speed;

  ///列数
  final int columns;

  ///棋盘宽度
  final double width;

  ///棋盘高度
  double? height;

  ///棋盘
  CheckerBoard? _board;

  ///蛇
  Snake? _snake;
  @override
  _SnakeWidgetState createState() => _SnakeWidgetState();
}

///状态
class _SnakeWidgetState extends State<SnakeWidget> {
  //状态
  GameState state = GameState.ready;
  /** 球 */
  Point<double>? ball;

  ///控制器
  GameController? _controller;

  EventBus bus = EventBus();

  // 状态初始化
  @override
  void initState() {
    super.initState();
    // 初始化控制器和球的位置
    _controller = GameController(
        snake: widget._snake, board: widget._board, speed: widget.speed);
    ball = (_controller as GameController).ball;

    // 自动右拐
    // _controller?.auto = true;
    //监听与更新
    _controller?.addListener(() {
      setState(() {
        state = (_controller as GameController).state;
        if (ball != _controller?.ball) {
          print('更新 ball');
          ball = _controller?.ball;
        }
      });
    });
    // start();
    // 监听事件
    bus.on('moveTo', (state) {
      print('moveto event');
      switch (state) {
        case ControllSign.left:
          _controller?.turnWest();
          break;
        case ControllSign.top:
          _controller?.turnNorth();
          break;
        case ControllSign.right:
          _controller?.turnEast();
          break;
        case ControllSign.bottom:
          _controller?.turnSouth();
          break;
      }
    });
    // 开始
    bus.on('gameStart', (res) {
      start();
    });
    bus.on('gameStop', (res) {
      stop();
    });
    bus.on('gameReset', (res) {
      reset();
    });
  }

  // 构建
  @override
  Widget build(BuildContext context) {
    var board = widget._board as CheckerBoard;
    return SizedBox(
      height: widget.height,
      width: widget.width,
      child: Stack(
        children: [
          ...getBody(),
          // 小球
          Positioned(
            left: (ball as Point<double>).x,
            top: (ball as Point<double>).y,
            child: Container(
              height: board.cellwidth,
              width: board.cellwidth,
              color: Colors.white,
            ),
          ),
          //如果赢了
          if (state == GameState.win)
            Positioned(child: createOver(state))
          // 如果输了
          else if (state == GameState.lose)
            Positioned(child: createOver(state))
        ],
      ),
    );
  }

  //重置
  void reset() {
    _controller?.reset();
  }

  //开始
  void start() {
    _controller?.start();
  }

  //结束
  void stop() {
    _controller?.stop();
  }

  ///获取蛇身
  List<Widget> getBody() {
    List<Point<double>> positions = (widget._snake as Snake).positions;
    double width = (widget._board as CheckerBoard).cellwidth;

    return positions.map((point) {
      var color = Colors.lightBlue[300];
      if (positions.first == point) {
        color = Colors.pink;
      }
      return Positioned(
          left: point.x,
          top: point.y,
          child: Container(color: color, height: width, width: width));
    }).toList();
  }

  /**获取展示板 */
  Widget createOver(GameState state) {
    var str, style;
    if (state == GameState.win) {
      str = '你赢了';
      style = TextStyle(color: Colors.green);
    } else if (state == GameState.lose) {
      str = '你输了';
      style = TextStyle(color: Colors.red);
    }
    return SizedBox(
      height: double.infinity,
      width: double.infinity,
      child: Container(
        height: double.infinity,
        width: double.infinity,
        color: Colors.black.withAlpha(100),
        child: Center(
          child: Container(
            padding: EdgeInsets.all(5),
            color: Colors.white.withAlpha(150),
            child: Text(
              str,
              style: style,
            ),
          ),
        ),
      ),
    );
  }
}
